package com.cff.shorturl.manager;

import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.cff.shorturl.cache.Cache;

public class LocalCacheManager extends CacheManager {
	private Map<String, Cache> cacheMap = new ConcurrentHashMap<>();

	private LocalCacheManager() {
		super();
	}

	private static class CacheManagerHolder {
		static CacheManager instance = new LocalCacheManager();
	}

	public static CacheManager getInstance() {
		return CacheManagerHolder.instance;
	}

	@Override
	public void clearAll() {
		cacheMap.clear();
	}

	@Override
	public Cache getCache(String key) {
		if (cacheExpiredOrNull(key)) {
			return null;
		}
		return cacheMap.get(key);
	}

	private boolean cacheExpiredOrNull(String key) {
		Cache cache = cacheMap.get(key);
		if (cache == null)
			return true;
		long nowDt = System.currentTimeMillis(); // 系统当前的毫秒数
		long cacheDt = cache.getTimeOut(); // 缓存内的过期毫秒数
		if (cacheDt <= 0 || cacheDt + cache.getStart() < nowDt) {
			return false;	
		} else { // 大于过期时间 即过期
			if(!cache.isHasLoad()){
				cacheMap.remove(key);
				return true;
			}
			try {
				cache.loadToCache();
			} catch (SQLException e) {
				e.printStackTrace();
				return true;
			}
			return false;
		}
	}

	@Override
	// 载入缓存
	public void putCache(String key, Cache obj) {
		cacheMap.put(key, obj);
	}

	// 载入缓存
	@Override
	public void putCache(String key, String value) {		
		cacheMap.put(key, new Cache(){
			@Override
			public void init() {
				setKey(key);
				setValue(value);
				setStart(System.currentTimeMillis());
				setTimeOut(-1);
			}

			@Override
			public void loadToCache() {
				
			}	 
		});
	}

	@Override
	public String getString(String key) {
		Cache cache = getCache(key);
		if (cache == null)
			return null;
		return cache.getValue().toString();
	}

}
